
package node;

import java.rmi.AccessException;
import java.rmi.AlreadyBoundException;
import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.Registry;

/**
 * 
 * This class validates the value for M anytime there is an input for M and also 
 * there is a validation for the node.
 * @author TCSS 558 Team 6
 * @version Spring 2013
 * 
 */
public class Validator
{
/* Constructor for class*/
  public Validator()
  {
    // do nothing
  }
/**
 * The main method to validate the node.
 * @param the_nodes .
 * @param the_node 
 * @param the_m  
 * @return .
 */
  public static int validateNode(final String[] the_nodes, final String the_node,
                                 final int the_m)
  {
    int node = 0;
    try
    {
      node = Integer.parseInt(the_node);
      // VERIFY node_id has a legal value - i.e. it is in 0 to 2^m-1 range
      if (node < 0 || node >= (1 << the_m))
      {
        throw new NumberFormatException();
      }
      // verify if node_id is not a duplicate //
      for (int i = 0; i != the_nodes.length; ++i)
      {
        if (the_nodes[i].equals(Conversion.IntToString(node)))
        {
          throw new AlreadyBoundException();
        }
      }
    }
    catch (final NumberFormatException e)
    {
      System.err.println("Invalid value of node id!");
      System.exit(1);
    }
    catch (final AlreadyBoundException e)
    {
      System.err.println("This node id is existed!");
      // this is fine for now - may be we can pick a node_id for the user?
      // implementation beyond scope of assignment for now
      System.exit(1);
    }
    return node;
  }

  /**
   * The main method to validate M.
   * @param the_registry .
   * @param the_m .
   * @return . 
   * @throws AccessException 
   * @throws RemoteException 
   * @throws NotBoundException  
   */
  public static int ValidateM(final Registry the_registry, final String the_m)
      throws AccessException, RemoteException, NotBoundException
  {
    int Mvalue = 0;
    try
    {
      Mvalue = Integer.parseInt(the_m);
      final String[] registered_nodes = the_registry.list();
      if (registered_nodes.length != 0)
      {
        final Node n = (Node) the_registry.lookup(registered_nodes[0]);
        final int m = n.getMValue();
        if (m != Mvalue)
        {
          System.err.println("The m value has already set to " + m);
          System.exit(1);
        }
      }
    }
    catch (final NumberFormatException e)
    {
      System.err.println("Invalid value of M!");
      System.exit(1);
    }
    return Mvalue;
  }
  public static int validate(Registry registry, String string)
  {
    // TODO Auto-generated method stub
    return 0;
  }

}
